package org.toolbook.validator;

import org.springframework.util.StringUtils;
import org.toolbook.model.User;
import org.toolbook.util.PropUtil;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.jfinal.validate.Validator;
/**
 * 修改密码的验证器
 * @author meigang
 * @date 2015-06-21 22:09
 *
 */
public class UploadHeadValidator extends Validator{

	@Override
	protected void validate(Controller c) {
		//得到文件head
		User u = c.getSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"));
		UploadFile head  = c.getFile("head", 
				PathKit.getWebRootPath() + "/head/" + u.get("id"));
		String fileExt = head.getFileName();
		//验证扩展名
		String[] exts = PropUtil.getProperty("upload_head_ext").split(",");
		boolean b = false;
		for(String ext : exts){
			if(ext.equals(StringUtils.getFilenameExtension(fileExt).toLowerCase())){
				b = true;
			}
		}
		if(!b){
			addError("ext_info", "不被支持的文件后缀");
		}
		//验证大小
		if(head.getFile().length() > Integer.parseInt(PropUtil.getProperty("upload_head_size")) * 1024 * 1024){
			addError("size_info", "头像文件超出大小");
		}
	}

	@Override
	protected void handleError(Controller c) {
		c.keepPara("head");
		c.setAttr("nopass", 1);
		c.render("/WEB-INF/pages/fc/user/updateHead.jsp");
	}

}
